package Timer;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTest {

	private static final long PERIOD_DAY = 1000;

	public static void main(String[] args) {
		TimerTest.runTimer(16, 49, new TimerTask() {

			@Override
			public void run() {
				System.out.println(new Date().getTime());
			}
		});
	}

	/**
	 * 指定固定的时间点执行任务
	 * 
	 * @param point
	 *            固定的时间点
	 * @param task
	 *            任务
	 */
	public static void runTimer(int point, TimerTask task) {
		runTimer(point, 0, task);
	}

	public static void runTimer(int point, int minute, TimerTask task) {
		Timer timer = new Timer();

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, point);
		calendar.set(Calendar.MINUTE, minute);
		calendar.set(Calendar.SECOND, 0);
		Date date = calendar.getTime();
		if (date.before(new Date())) {
			date = addDay(date, 1);
		}

		timer.schedule(task, date, PERIOD_DAY);
	}

	/**
	 * 添加天数
	 * 
	 * @param date
	 *            当期的日期
	 * @param num
	 *            添加的天数
	 * @return
	 */
	public static Date addDay(Date date, int num) {
		Calendar startDT = Calendar.getInstance();
		startDT.setTime(date);
		startDT.add(Calendar.DAY_OF_MONTH, num);
		return startDT.getTime();
	}
}
